<template>
  <!-- 仓库列表 -->
  <div class="content">
    <jc-button
      v-if="msg!==1"
      :btn-arr="['reload', 'pass', 'sub', 'option', 'remove', 'newy']"
      :disab-arr="['copy', 'close', 'cancel', 'com1', 'com2', 'chart', 'freeze']"
      @newly="newly"
      @submit="submit(1)"
      @noSubmit="submit(2)"
      @audit="audit(1)"
      @noAudit="audit(2)"
      @forbidden="using(1)"
      @startUsing="using(2)"
      @del="delet"
      @refresh="handleGetUntreated"
      @toExcel="handleExport"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="handleQuerySonClass"
        />
        <el-button type="primary" class="btn" size="mini" @click="handleQuerySonClass">{{ $t('btn.search') }}</el-button>
        <filtration
          v-if="msg!==1"
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="handleQuerySonClass"
        />
      </div>
    </div>
    <div>
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        :table-height="tableHeight"
        sortable
        table-selection
        @selectionChange="handleSelectAll"
        @clickRow="warehouseSelectRow"
      >
        <!--仓库编号-->
        <template v-slot:btnStates="col">
          <el-link type="primary" @click="detailPurchase(col.scope.row)">{{ col.scope.row.fnumber }}</el-link>
        </template>
        <!--        审核状态-->
        <template v-slot:btnState="col">
          <el-tag :type="col.scope.row.stateColor">{{ col.scope.row.fdocumentstatus }}</el-tag>
        </template>
        <!--        禁用状态-->
        <template v-slot:tagSlot="col">
          <el-tag v-if="col.scope.row.fforbidstatus === 'A'">{{ $t('market.normal') }}</el-tag>
          <el-tag v-else type="danger">{{ $t('btn.disab') }}<!--禁用--></el-tag>
        </template>
      </jc-table>
      <!--    分页器-->
      <div class="footer">
        <jc-pagination
          :total="total"
          :page.sync="currentPage"
          :limit.sync="size"
          @pagination="handleGetUntreated"
        />
      </div>
    </div>
    <el-dialog
      v-dialogDrag
      :title="stockTitle"
      model
      :visible.sync="isStockDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="purchaseRef" :model="prodValue" label-width="100px" :disabled="isDisabled">
        <el-form-item :label="$t('market.stockname')">
          <el-input v-model.trim="prodValue.fname" size="mini" />
        </el-form-item>
        <el-form-item :label="$t('market.stockNumber')">
          <el-input v-model.trim="prodValue.fnumber" disabled size="mini" />
        </el-form-item>
        <el-form-item :label="$t('market.stockType')">
          <el-select v-model.trim="prodValue.ftype" size="mini" filterable>
            <el-option
              v-for="(item, index) in billtypes"
              :key="index"
              :label="item.fname"
              :value="item.fid"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('market.address')">
          <el-input v-model.trim="prodValue.faddress" size="mini" />
        </el-form-item>
        <el-form-item :label="$t('market.stocker')">
          <el-select v-model="prodValue.fstockerId" size="mini">
            <el-option
              v-for="(item, index) in marketDialogData"
              :key="index"
              :label="item.fuserName"
              :value="item.fuserId"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('market.descrip')">
          <el-input v-model.trim="prodValue.fdescripTion" size="mini" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isStockDialog=false">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" :disabled="isDisabled" @click="addStock">{{ $t('btn.save') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  ableWmsStock, deleteWmsStock,
  disableWmsStock, insertWmsStock,
  notreviewWmsStock,
  notsubmitWmsStock, queryWmsBdStockList, reviewWmsStock,
  submitWmsStock, updateWmsStock
} from '@/api/wms/stock'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import { notoMxBmina, toMxBmina } from '@/components/ToMxamineState'
import jcButton from '@/components/Button'
import { querySalesperson, queryViewItem } from '@/api/marketManage/marketOrder'

export default {
  // name: 'ForthwithRep',
  components: {
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  props: {
    msg: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isStockDialog: false,
      isDisabled: false,
      stockTitle: '',
      ftype: 51,
      total: 0, // 总条目
      currentPage: 1, // 当前页
      size: 200, // 每页显示多少条数据
      // 表头
      tableData: [], // 销售数据
      tableHeight: '73vh',
      tableHeader: [
        { label: this.$t('market.stock2'), prop: 'fname' },
        { label: this.$t('market.stockNumber'), type: 'states', prop: 'fnumber' },
        { label: this.$t('market.stockType'), prop: 'ftypeName' },
        { label: this.$t('market.stocker'), prop: 'fstockerName' },
        { label: this.$t('market.address'), prop: 'faddress' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus' },
        { label: this.$t('market.forbidStatu'), type: 'tag', prop: 'fforbidstatus' }
      ],
      tableHeader1: [],
      marketDialogData: [], // 仓管
      billtypes: [], // 仓库类型
      prodValue: {}
    }
  },
  created() {
    this.handleGetUntreated()
    this.tableHeader1 = this.tableHeader
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 240px)' : '70vh'
  },
  methods: {
    newly() {
      this.prodValue = {
        faddress: '',
        ftype: 170,
        fstockerId: '',
        fstockerName: '',
        fdescripTion: ''
      }
      this.isStockDialog = true
      this.stockTitle = '新增仓库'
      this.marketDialogData.length === 0 && this.querySalesperson() // 仓管
      this.billtypes.length === 0 && this.queryTBasBilltype() // 仓库类型
    },
    // 修改
    detailPurchase(ev) {
      this.isDisabled = ev.fdocumentstatus === this.$t('market.state1') || ev.fdocumentstatus === this.$t('market.state2')
      this.prodValue = { ...ev }
      this.isStockDialog = true
      this.stockTitle = '仓库详情'
      this.marketDialogData.length === 0 && this.querySalesperson() // 仓管
      this.billtypes.length === 0 && this.queryTBasBilltype() // 仓库类型
    },
    // 新增 修改仓库
    addStock() {
      const DATA = {
        ...notoMxBmina(this.prodValue)
      }
      const api = this.prodValue.fid ? updateWmsStock : insertWmsStock
      api(DATA).then(res => {
        if (res.code === 0) {
          this.handleGetUntreated()
          this.isStockDialog = false
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        }
      })
    },
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeader.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeader.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryWmsBdStockList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.list.map(item => {
                if (item.fforbidstatus === 'A') {
                  item.fforbidstatus = '正常'
                } else {
                  item.fforbidstatus = '禁用'
                }
                return toMxBmina(item)
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '仓库列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 查询仓管员
    async querySalesperson() {
      this.ismarketlDialog = true
      const DATA = {
        staffType: 3, // 仓管员
        pageNum: 1, // 当前页
        pageSize: 200 // 每页显示多少条数据
      }
      const { data: RES } = await querySalesperson(DATA)
      this.marketDialogData = RES.list
    },
    // 查询仓库类型
    async queryTBasBilltype() {
      const { data: RES } = await queryViewItem({ viewName: 'SX_STOCKTYPE' })
      this.billtypes = RES.list
    },
    // 获取仓库数据
    async handleGetUntreated(ev) {
      this.loading = true
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        pageNum: this.currentPage,
        pageSize: this.size,
        search: this.searCollData.concat(this.details),
        fnumberGroup: this.fnumberGroup
      }
      const RES = await queryWmsBdStockList(DATA)
      this.tableData = RES.data.list
      this.tableData.map(item => {
        return toMxBmina(item)
      })
      this.total = RES.data.total
      this.loading = false
    },
    // 搜索
    handleQuerySonClass(ev) {
      this.currentPage = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.handleGetUntreated(ev.detail)
      } else {
        this.handleGetUntreated()
      }
    },
    // 向父传参
    warehouseSelectRow(ev) {
      this.$emit('client', ev)
    },
    // 选中
    handleSelectAll(val) {
      this.val = val
      this.selectVal = []
      val.forEach(item => {
        item.fnumber && this.selectVal.push(item.fnumber)
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.handleGetUntreated()
        this.selectVal = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 提交
    async submit(ev) {
      const api = ev === 1 ? submitWmsStock : notsubmitWmsStock
      this.toExamineFun(api)
    },
    // 审核
    async audit(ev) {
      const api = ev === 1 ? reviewWmsStock : notreviewWmsStock
      this.toExamineFun(api)
    },
    // 禁用启用
    async using(ev) {
      const api = ev === 1 ? disableWmsStock : ableWmsStock
      this.toExamineFun(api)
    },
    // 删除
    delet() {
      this.$confirm('确认要删除么？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = deleteWmsStock
        this.toExamineFun(api)
      })
    },
    handleClose() {
      this.prodValue = {}
      this.isStockDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.content {
  @include listBom;
  .el-form {
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  .header{
    position:relative;
    margin-bottom: 5px;
    .header-name{
      width: 100%;
    }
    .btn{
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
}
</style>
